﻿
using JNPF.Logging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PARK.Common.WeChat.Pay.Model.Close;
using PARK.Consumer;
using PARK.Consumer.Interfaces.ConsumRefund;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.TaskScheduler.Interfaces;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace PARK.TaskScheduler
{
    /// <summary>
    /// 体测任务队列
    /// </summary>
    [ApiDescriptionSettings(Tag = "RefundJob", Name = "refundJobtask", Order = 220)]
    [Route("api/[controller]")]
    public class RefundJobService : BackgroundService, IRefundJobService, IDynamicApiController, ITransient
    {
        private readonly SqlSugarScope _db;
        private readonly int _times = 0;
        private readonly IConsumRefundRepository _ConsumRefundRepository;
        public RefundJobService(ILogger<RefundJobService> logger,
            ISqlSugarClient db,
            IConsumRefundRepository consumRefundRepository)
        {
            _db = (SqlSugarScope)db;
            _ConsumRefundRepository = consumRefundRepository;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {

        }
        /// <summary>
        /// 启动自启动任务
        /// </summary>
        [NonAction]
        public async void StartTimerJob()
        {
            new LoggEx().Info("退款队列开始执行");
            CancellationToken stoppingToken = new CancellationToken();
            while (!stoppingToken.IsCancellationRequested)
            {
                await new TaskFactory().StartNew(() =>
                {
                    try
                    {
                        new LoggEx().Info("退款队列开始执行:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        Runrefund();
                    }
                    catch (Exception e)
                    {
                        new LoggEx().Info("退款队列异常:=============失败=====" + e.Message);
                    }
                    //定时任务休眠
                    Thread.Sleep(60 * 1000);
                });
            }
        }

        #region 执行退款队列
        /// <summary>
        /// 执行退款队列
        /// </summary>
        void Runrefund()
        {
            //存储过程获取待退款任务
            var Pars = new List<SugarParameter>();
            DataTable ds = _db.Ado.UseStoredProcedure().GetDataTable("P_Get_refundTask", Pars);
            if (ds != null && ds.Rows.Count > 0)
            {
                for (int i = 0; i < ds.Rows.Count; i++)
                {
                    new LoggEx().Info("进入退款执行方法1....");
                    var _Refund = new RefundModel();
                    _Refund.taskId = ds.Rows[i]["taskId"].ToString();
                    _Refund.CompanyId = ds.Rows[i]["CompanyId"].ToString();
                    _Refund.mch_id = "";
                    _Refund.OutRefundNo = ds.Rows[i]["out_refund_no"].ToString();
                    _Refund.OutTradeNo = ds.Rows[i]["out_trade_no"].ToString();
                    _Refund.TotalFee = Convert.ToInt32(Convert.ToDecimal(ds.Rows[i]["totalAmt"].ToString()) * 100);
                    _Refund.RefundFee = Convert.ToInt32(Convert.ToDecimal(ds.Rows[i]["refundAmt"].ToString()) * 100);
                    new LoggEx().Info("进入退款执行方法2.........");
                    _ConsumRefundRepository.RefundOrder(_Refund);
                }
            }
        }
        #endregion
    }
}
